var m_CurrentPageButton = "#ButtonLogInPage";

var spinnerOpts = {
		  lines: 13, // The number of lines to draw
		  length: 7, // The length of each line
		  width: 3, // The line thickness
		  radius: 7, // The radius of the inner circle
		  corners: 1, // Corner roundness (0..1)
		  rotate: 0, // The rotation offset
		  color: '#FFFFFF', // #rgb or #rrggbb
		  speed: 1, // Rounds per second
		  trail: 60, // Afterglow percentage
		  shadow: false, // Whether to render a shadow
		  hwaccel: false, // Whether to use hardware acceleration
		  className: 'spinner', // The CSS class to assign to the spinner
		  zIndex: 2e9, // The z-index (defaults to 2000000000)
		  top: 'auto', // Top position relative to parent in px
		  left: 'auto' // Left position relative to parent in px
		};

var spinnerObject = new Spinner(spinnerOpts);

//This function is to fix iOS6-iOS6.0.1 POST caching bug.  
$.ajaxSetup({
    type: 'POST',
    headers: { "cache-control": "no-cache" }
});

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    "numeric-pre": function ( a ) {
    	if (a==""){
    		return Number.MAX_VALUE;
    	} else{
    		return a;
    	}
    }
});

$(document).ready(function(){
	mainPageNavigationButtonClicked("Profile", "#ButtonProfile");
});

function escapeStr(i_Str){
	i_Str = i_Str.split('\\').join('\\\\');
	i_Str = replaceAll(i_Str,"'","\\'");
	i_Str = replaceAll(i_Str,"\"","\\\"");
	i_Str = replaceAll(i_Str,"%","\\%");
	i_Str = replaceAll(i_Str,"_","\\_");
	return i_Str;
}

function replaceAll(txt, replace, with_this) {
	var newStr = txt.replace(new RegExp(replace, 'g'),with_this); 
	return newStr;
	}

function mainPageNavigationButtonClicked(i_WhereToNavigate, i_ButtonToAddClass)
{
	var target = document.getElementById(i_ButtonToAddClass.substring(1));
	var targetParent = target.parentNode;
	spinnerObject.spin(targetParent);
	var toUrl='#';
	switch (i_WhereToNavigate) {
	case 'Profile':
		toUrl = 'Profile.jsp';
		break;
	case 'Games':
		toUrl = 'ShowGamesInTeam.jsp';
		break;
	case 'Players':
		toUrl = 'ShowPlayersInTeam.jsp';
		break;
	case 'CreateNewGame':
		toUrl = 'CreateNewGame.jsp';
		break;
	case 'JoinRequests':
		toUrl = 'ShowJoinRequests.jsp';
		break;
	default:
		break;
	}
       jQuery.ajax({  
       url: toUrl, 
       type : "POST", 
       error: function(jqXHR, textStatus, errorThrown) {
         console.log('Failed to send ajax');
         }, 
       success: function(page) {  
    	 spinnerObject.stop();
         changeDivMainContainer(page);
         addClassButtonNavigationClicked(i_ButtonToAddClass);
  }});
}

function addClassButtonNavigationClicked(i_ButtonToAddClass){
        if(i_ButtonToAddClass != m_CurrentPageButton)
        {
            $(m_CurrentPageButton).removeClass('ButtonNavigationClicked');
            $(m_CurrentPageButton).addClass('ButtonNavigationNotClicked');
            $(i_ButtonToAddClass).removeClass('ButtonNavigationNotClicked');
            $(i_ButtonToAddClass).addClass('ButtonNavigationClicked');
            m_CurrentPageButton = i_ButtonToAddClass;
            $('#LinkLogin').show();
        }
    }


function changeDivMainContainer(i_data){
    $('#DivMainContainer').fadeOut("medium",function(){ 
        $('#DivMainContainer').empty(); 
        $('#DivMainContainer').append(i_data).fadeIn("medium");});                     
 }

function SignOutClicked() {
    jQuery.ajax({  
        url: 'registration',
        data: "action=LogOut",
        timeout: 2000, 
        error: function() {
          console.log('Failed to send ajax');
          }, 
        success: function() { 
        	window.location = 'index.jsp';
   }});
}

function EditProfile() {
	$('#ButtonEditProfile').fadeOut("slow", function(){
	$('#UserBirthdayProfile').fadeIn("slow");
	$('#UserBirthdayProfileInfo').fadeIn("slow");
	$('#UserNameProfile').removeAttr("disabled");
	$('#UserPasswordProfile').removeAttr("disabled");
	$('#SpanUserRePasswordProfile').fadeIn("slow");
	$('#ButtonSaveChangeInfoProfile').fadeIn("slow");
	$('#ButtonCancelChangeInfoProfile').fadeIn("slow");});
}

function ChangeProfileInfo(saveOrCancel) {
	if(saveOrCancel == "save")
		{
			if($('#UserNameProfile').val().length > 0 || $('#UserNameProfile').val() == " ")
			{
				if($('#UserPasswordProfile').val() == $('#UserRePasswordProfile').val())
					{
			    jQuery.ajax({ 
			        data: "action=changeProfileInfo&UserBirthdayProfile="+$('#UserBirthdayProfile').val()+"&UserNameProfile="+$('#UserNameProfile').val()+"&UserPasswordProfile="+$('#UserPasswordProfile').val(), 
			        url: 'servletMainPage',
			        
			        timeout: 2000, 
			        error: function() {
			          console.log('Failed to send ajax');
			          }, 
			        success: function() { 
			        	mainPageNavigationButtonClicked("Profile", "#ButtonProfile");
			   }});
					}
				else{
					$("#DivErrorInfo").empty();
					$("#DivErrorInfo").html("<h4>Password != RePassword</h4>").fadeIn("slow");	
				}
			}
		else
			{
				$("#DivErrorInfo").empty();
				$("#DivErrorInfo").html("<h4>No Name?!</h4>").fadeIn("slow");
			}
		}
	else // Cancel
		{
			mainPageNavigationButtonClicked("Profile", "#ButtonProfile");
		}
}